package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.admin.entity.AdChannel;
import com.heima.admin.mapper.AdChannelMapper;
import com.heima.admin.service.AdChannelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.PageResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.model.admin.dtos.ChannelDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 频道信息表 服务实现类
 * </p>
 *
 * @author 黑虎阿福
 * @since 2022-04-26
 */
@Service
public class AdChannelServiceImpl extends ServiceImpl<AdChannelMapper, AdChannel> implements AdChannelService {

    /**
     * 分页查询
     *
     * @param channelDto
     * @return
     */
    @Override
    public PageResult<ChannelDto> findByPage(ChannelDto channelDto) {
        //1.设置分页
        Page<AdChannel> iPage = new Page<>(channelDto.getPage(),channelDto.getSize());
        //2.设置查询条件
        LambdaQueryWrapper<AdChannel> wrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(channelDto.getName())){
            //模糊查询
            wrapper.like(AdChannel::getName,channelDto.getName());
        }
        IPage<AdChannel> page = page(iPage, wrapper);
        //3.封装信息
        if(page==null || CollectionUtils.isEmpty(page.getRecords())){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //4.转化为dto对象
        List<ChannelDto> data = BeanHelper.copyWithCollection(page.getRecords(), ChannelDto.class);
        return new PageResult<>(channelDto.getPage(),channelDto.getSize(), page.getTotal(), data);
    }

    /**
     * 根据id删除频道
     *
     * @param id
     * @return
     */
    @Override
    public void deleteById(Long id) {
        //1.先判断状态
        AdChannel adChannel = getById(id);
        if (adChannel==null){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (adChannel.getStatus()){
            throw new LeadException(AppHttpCodeEnum.DATA_CAN_NOT_DEL);
        }
        boolean removeById = removeById(id);
        if (!removeById){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
    }
}
